<!-- 添加企业 编辑企业 -->
<script setup lang='ts' name="org-role-add">
import type { FormInstance } from 'element-plus'

import { getOcrIdCard } from '@fl/api/anjutong'
import { addCompanyOrg, getAllCompanyOrg, getNewCompanyOrgDetail, useGetCatTypeDictInfo } from '@fl/api/iam-api'
import type { AddressValue } from '@fl/api/joint-api'
import { addCompany, auditCompany, getCompanyById, getCompanyByLoginUser, updateCompany } from '@fl/api/joint-api'
import Address from '@/components/address.vue'
import FlUpload from '@fl/components/fl-upload.vue'
import { useUserStore } from '@fl/store/modules/user'
import { formatTime, readFileAsBase64 } from '@fl/utils'
import { ElButton, ElCard, ElCol, ElDatePicker, ElForm, ElFormItem, ElInput, ElMessage, ElOption, ElRadio, ElRadioGroup, ElRow, ElSelect, ElSwitch } from 'element-plus'
import { nextTick, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { CAT_TYPE } from '../constant'
import { useDicts } from '../hooks/use-dicts'
import { useForm } from './hooks/use-form'
import { useRule } from './hooks/use-rule'
import { useSessionStorage } from '@vueuse/core'

const props = withDefaults(defineProps<{
    modelValue: boolean
    showId?: string
}>(), {

})
const emits = defineEmits(['update:modelValue', 'confirm', 'goto'])

const userStore = useUserStore()
const { go } = useRouter()
const { rules } = useRule()

const { form } = useForm()
const router = useRouter()
const route = useRoute()
const formRef = ref()
const dueDate = ref<any>({})
const loading = ref<boolean>(false)
const isEdit = ref<boolean>(false)
const isLoading = ref<boolean>(true)
const isAdmin = ref<boolean>(userStore.getUserInfo?.userFlag === '1')
const addressStr = ref('')
const addressObject = ref<AddressValue>()

const { showId } = toRefs(props)

function addressChange(value: any) {
    if (value.provinceCode && value.cityCode && value.areaCode && value.address) {
        // 保存完整的地址对象
        addressObject.value = value
        form.registeredAddress = [value.provinceName, value.cityName, value.areaName, value.address].join(',')
        // // 更新表单中的地址字符串
        addressStr.value = [
        `${value.provinceCode}-${value.provinceName}`,
        `${value.cityCode}-${value.cityName}`,
        `${value.areaCode}-${value.areaName}`,
        value.address,
        ].join(',')
    }
    else {
        addressObject.value = {
            provinceCode: '',
            provinceName: '',
            cityCode: '',
            cityName: '',
            areaCode: '',
            areaName: '',
            address: '',
        }
        form.registeredAddress = ''
        // // 更新表单中的地址字符串
        addressStr.value = ''
    }
}

async function doSave(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    await formEl.validate((valid, fields) => {
        if (valid)
            saveData()
        else
            console.log('error!', fields)
    })
}

async function saveData() {
    const data: any = {
        ...form,
        ...addressObject.value,
        idCardBack: Array.isArray(form.idCardBack) ? form.idCardBack?.[0]?.url || '' : form.idCardBack,
        idCardFront: Array.isArray(form.idCardFront) ? form.idCardFront?.[0]?.url || '' : form.idCardFront,
        businessImg: Array.isArray(form.businessImg) ? form.businessImg?.[0]?.url || '' : form.businessImg,
        registeredAddress: form.registeredAddress,
        auditStatus: 1,

    }
    console.log('save前data', data)
    // 编辑必传
    if (isEdit.value)
        data.id = form.id

    sendFlow(data)
}

const { isPending, mutateAsync: runUpdateCompany } = useMutation({
    // mutationFn: (data: ILoginRequest) => _rOauthToken2(data),
    mutationFn: data => updateCompany(data),
    onSuccess: async (data) => {
        // console.log('🚀 ~ updateCompany ~ data:', data)

        ElMessage.success('保存成功')
        setTimeout(() => {
            goback()
        }, 1000)
    },
})

const { isPending: updateLoading, mutateAsync: runAddCompany } = useMutation({
    mutationFn: data => addCompany(data),
    onSuccess: async (data) => {
        console.log('🚀 ~ addCompany ~ data:', data)
        ElMessage.success('保存成功')
        setTimeout(() => {
            goback()
        }, 1000)
    },
})
const { isPending: auditLoading, mutateAsync: runAudit } = useMutation({
    mutationFn: data => auditCompany(data),
    onSuccess: async (data) => {
        console.log('🚀 ~ addCompany ~ data:', data)
        ElMessage.success('保存成功')
        setTimeout(() => {
            goback()
        }, 1000)
    },
})

function audit(status: number) {
    const obj = {
        companyId: form.id,
        auditStatus: String(status),
    }

    runAudit(obj)
}

async function sendFlow(data: any) {
    data.createBy = userStore.getUserInfo?.id
    data.createdName = userStore.getUserInfo?.name
    console.log('保存sendFlow', data)

    if (isEdit.value) {
        runUpdateCompany(data)
    }
    else {
        runAddCompany(data)
    }
}

function legalCardFrontChange() {
    formRef.value.clearValidate('idCardFront')
}

function goback() {
    // router.replace('/joint/business-management/company-org')
    // emits('update:modelValue', true)
    emits('confirm')
    emits('goto', 'list')
}

function fieldCompany(res) {
    console.log('🚀 ~ fieldCompany ~ res:', res)

    if (res.registeredAddress) {
        const [p = '', c, a, addr] = res.registeredAddress.split(',')
        const {
            provinceCode,
            provinceName,
            cityCode,
            cityName,
            areaCode,
            areaName,
        } = res

        // 修改这里，添加省市区的编码
        addressStr.value = [
                `${provinceCode}-${provinceName}`,
                `${cityCode}-${cityName}`,
                `${areaCode}-${areaName}`,
                addr,
        ].join(',')

        // 保存完整的地址对象
        addressObject.value = {
            provinceCode,
            provinceName,
            cityCode,
            cityName,
            areaCode,
            areaName,
            address: addr,
        }
    }

    // 逐个属性赋值，保持响应式
    Object.keys(res).forEach((key) => {
        form[key] = res[key] || ''
    })

    isLoading.value = false
}
async function getUserCompany() {
    isLoading.value = true
    try {
        const res = await getCompanyByLoginUser()
        if (res?.companyCode) {
            useSessionStorage('companyId', res.id)
            useSessionStorage('companyDetail', res)
            // console.log('🚀 ~ getAllCompanyOrg ~ res:', res)
            fieldCompany(res)
        }
        else {
            isLoading.value = false
        }
    }
    catch (error) {
        isLoading.value = false
    }
}
function init(val: any) {
    const id = val.query?.id || showId.value
    isEdit.value = !!id
    console.log('init', val)

    if (!isEdit.value) {
        isLoading.value = false
        return
    }

    // 详情
    getCompanyById(id).then((res: any) => {
        console.log('🚀 ~ getCompanyById ~ res:', res)

        if (res?.companyCode) {
            fieldCompany(res)
            console.log('企业详情form', form)
        }
        else {
            isLoading.value = false
        }
    })
}
const hasReturn = ref(true)

onMounted(() => {
    const userInfo = userStore.getUserInfo
    // console.log('🚀 ~ generateHeaderMenu ~ userInfo:', userInfo)
    const { userFlag, userStep } = userInfo as any
    // 企业管理员进来就先创建企业，用的是前段写的路由
    if (userFlag === '2' && ['1', '2'].includes(userStep)) {
        hasReturn.value = false
        getUserCompany()
    }
})

watch(route, (val: any) => {
    init(val)
}, {
    deep: true,
    immediate: true,
})
</script>

<template>
    <ElCard class="mb-20">
        <ElRow v-if="hasReturn"
               class="mb-20"
        >
            <ElButton @click="goback">
                返回列表
            </ElButton>
        </ElRow>

        <el-skeleton v-if="isLoading"
                     animated
        />

        <ElForm v-else
                ref="formRef"
                :model="form"
                label-position="top"
                label-width="auto"
                :rules="rules"
        >
            <ElRow :gutter="20">
                <ElCol :span="12">
                    <ElFormItem label="企业名称"
                                prop="companyName"
                    >
                        <ElInput v-model="form.companyName"
                                 placeholder="请输入企业名称"
                                 :disabled="isEdit"
                        />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="12">
                    <ElFormItem label="企业简称"
                                prop="companyAbbreviation"
                    >
                        <ElInput v-model="form.companyAbbreviation"
                                 placeholder="请输入企业简称"
                        />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="12">
                    <ElFormItem label="统一社会信用代码"
                                prop="companyCode"
                    >
                        <ElInput v-model="form.companyCode"
                                 placeholder="请输入统一社会信用代码"
                                 :disabled="isEdit"
                        />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="12">
                    <ElFormItem label="企业联系电话"
                                prop="companyPhone"
                    >
                        <ElInput v-model="form.companyPhone"
                                 placeholder="请输入企业联系电话"
                                 maxlength="12"
                        />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="12">
                    <ElFormItem label="企业法人"
                                prop="legalName"
                    >
                        <ElInput v-model="form.legalName"
                                 placeholder="请输入企业法人姓名"
                        />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="12">
                    <ElFormItem label="法人证件号码"
                                prop="legalIdCard"
                    >
                        <ElInput v-model="form.legalIdCard"
                                 placeholder="请输入法人证件号码"
                                 maxlength="18"
                        />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElFormItem label="企业注册地址"
                        prop="registeredAddress"
            >
                <Address v-model="addressStr"
                         @change="addressChange"
                />
            </ElFormItem>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="营业执照"
                                prop="businessImg"
                                class="tip_box"
                    >
                        <FlUpload v-model="form.businessImg" />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="企业法人身份证(正面)"
                                prop="idCardFront"
                                class="tip_box"
                    >
                        <FlUpload v-model="form.idCardFront"
                                  @success="legalCardFrontChange"
                        />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="企业法人身份证(反面)"
                                prop="idCardBack"
                                class="tip_box"
                    >
                        <FlUpload v-model="form.idCardBack" />

                        <div v-if="dueDate.start"
                             class="tips"
                        >
                            <p>有效期:</p>

                            <p>{{ dueDate.start }} 至 {{ dueDate.end }}</p>
                        </div>
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <div v-if="isAdmin && form.auditStatus === '1'"
                 style="text-align: center;"
                 class="mb20 mt60"
            >
                <ElButton class="mx40"
                          :loading="auditLoading"
                          @click="audit(3)"
                >
                    驳回
                </ElButton>

                <ElButton type="primary"
                          class="mx40"
                          :loading="auditLoading"
                          @click="audit(2)"
                >
                    审批通过
                </ElButton>
            </div>

            <div v-else
                 style="text-align: center;"
                 class="mb20 mt60"
            >
                <ElButton class="mx40"
                          @click="goback"
                >
                    返回
                </ElButton>

                <ElButton type="primary"
                          class="mx40"
                          :loading="updateLoading || isPending"
                          @click="doSave(formRef)"
                >
                    提交保存
                </ElButton>
            </div>
        </ElForm>
    </ElCard>
</template>

<style lang="less" scoped>
.info-title {
    font-size: 16px;
    font-weight: 600;
    line-height: 60px;
    display: flex;
    align-items: center;
}

.tip_box {
    :deep(.el-form-item__content) {
        display: flex;
        flex-direction: row;
        align-items: flex-end;

        .tips {
            padding-left: 5px;
        }
    }
}
</style>
